package com.demo.blog.common.advice;

import com.demo.blog.pojo.response.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
// 统一返回结果，将数据转为json数据
public class ResponseAdvice implements ResponseBodyAdvice {
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
        /*
        * 返回 false 的情况
            作用：不处理任何控制器方法的返回值
            效果：beforeBodyWrite 方法不会被调用，返回值直接输出*/
        /*

        * 返回 true 的情况
            作用：对所有控制器方法的返回值都进行统一处理
            效果：无论返回什么类型的对象，都会通过 beforeBodyWrite 方法进行封装*/
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        if (body instanceof Result){
            return body;
        }
        if (body instanceof String){
            return objectMapper.writeValueAsString(Result.success(body));
        }
        return Result.success(body);

    }
}
